package com.game.logic.user.login;

import com.alibaba.fastjson.JSONObject;
import com.coment.dto.LiveData;
import com.coment.dto.LiveData.ApiType;
import com.coment.po.AnchorInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.game.dao.living.AnchorInfoDao;
import com.sdk.ks.KSResponse;
import com.sdk.ks.KSServiceImpl;
import com.sdk.ks.KsActionType;
import com.sdk.service.impl.DYServiceImpl;
import com.xs.action.dto.Message;
import com.xs.action.exection.ActionException;
import com.xs.build.server.websocket.channel.ClientManager;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class LoginService implements ILoginService {
    private static final String LOGIN_KEY = "anchorInfo:%s";
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${spring.application.env}")
    public String env;
    @Resource
    private DYServiceImpl dYService;
    @Resource
    private KSServiceImpl ksService;
    @Resource
    private AnchorInfoDao anchorInfoDao;

    @Override
    public String login(ChannelHandlerContext ctx, String apiType, String clientToken) {
        ApiType type = ApiType.fromValue(apiType);
        return switch (type) {
            case douyin -> DYLogin(ctx, clientToken);
            case kuaiShou -> KSLogin(ctx, clientToken);
        };
    }

    private String KSLogin(ChannelHandlerContext ctx, String roomCode) {
        AppEnv appEnv = AppEnv.formatOf(env);
        String token;
        if (roomCode.equals("testsfsdfasdfasdf4cdfvgbhnjkl44444444444444sdfffffffffffffffff22")) {
            return DEVLogin(ctx, ApiType.kuaiShou, roomCode);
        }

        switch (appEnv) {
            case Dev:
                return DEVLogin(ctx, ApiType.kuaiShou, roomCode);
            case test, produce:
                try {
                    KSResponse bind = ksService.bind(roomCode, KsActionType.start.getValue());
                    if (bind.getResult() != 1) {
                        throw new RuntimeException(bind.getErrorMsg());
                    }
                    LiveData.KSPayload.KSPayloadData.Payload.UserInfo userInfo =
                            JSONObject.parseObject(bind.getData(), LiveData.KSPayload.KSPayloadData.Payload.UserInfo.class);

                    AnchorInfo anchorInfo = new AnchorInfo(userInfo,roomCode);
                    anchorInfoDao.save(anchorInfo);
                    this.redisTemplate.opsForValue().set(LOGIN_KEY.formatted(anchorInfo.getId()), anchorInfo);
                    ClientManager.clientIdMap.put(
                            anchorInfo.getId().toString(),
                            ctx.channel().id().asLongText()
                    );
                    token = anchorInfo.getId().toString();
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                throw new ActionException("环境错误");
        }
        return token;
    }

    private String DYLogin(ChannelHandlerContext ctx, String clientToken) {
        AppEnv appEnv = AppEnv.formatOf(this.env);
        String token = null;
        switch (appEnv) {
            case Dev, test:
                return DEVLogin(ctx, ApiType.douyin, clientToken);
            case produce:
                LiveData.DyPayload.AnchorInfo anchorInfo = this.dYService.getRoomId(clientToken);
                if (anchorInfo == null) {
                    throw new ActionException("认证失败");
                }
                String anchorOpenId = anchorInfo.getAnchorOpenId();
                return token;
            default:
                throw new ActionException("环境错误");
        }
    }

    private String DEVLogin(ChannelHandlerContext ctx, ApiType apiType, String clientToken) {
        AnchorInfo anchorInfo = anchorInfoDao.searchOrCreateByApiTypeAndRoomId(apiType.getValue(), clientToken);
        this.redisTemplate.opsForValue().set(LOGIN_KEY.formatted(anchorInfo.getId()), anchorInfo);
        ClientManager.clientIdMap.put(anchorInfo.getId().toString(), ctx.channel().id().asLongText());
        return anchorInfo.getId().toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void interceptor(ChannelHandlerContext ctx, Message message) {
        if (message.ext.isEmpty()) {
            throw new ActionException("请先登录");
        } else {
            Map<String, Object> ext = message.getExt();
            Map<String, Object> o = (Map<String, Object>) ext.get("token");
            String anchorInfoId = (String) o.get("roomId");
            this.checkToken(ctx, LOGIN_KEY.formatted(anchorInfoId));
            String channelId = ctx.channel().id().asLongText();
            ClientManager.clientIdMap.put(anchorInfoId, channelId);
        }
    }

    @Override
    public void checkToken(ChannelHandlerContext ctx, String token) {
//        boolean b = this.redisTemplate.hasKey(token);
//        if (b) {
//            this.redisTemplate.expire(token, 30L, TimeUnit.MINUTES);
//        } else {
//            ctx.close();
//            throw new ActionException("请先登录");
//        }
    }
}

@Getter
@AllArgsConstructor
enum AppEnv {
    Dev("dev"),
    test("test"),
    produce("produce");
    private final String value;

    public static AppEnv formatOf(String env) {
        for (AppEnv value : values()) {
            if (value.value.equals(env)) {
                return value;
            }
        }
        throw new ActionException("环境错误");
    }
}
